package com.amt.olcacon.controller.flow;

import com.amt.olcacon.db.DerbyConfig;
import com.amt.olcacon.vo.GlobalResponse;
import com.amt.olcacon.vo.request.PropertyRequest;
import io.micrometer.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.openlca.core.DataDir;
import org.openlca.core.database.FlowPropertyDao;
import org.openlca.core.model.FlowProperty;
import org.openlca.core.model.UnitGroup;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * property api
 *
 * @Author: yangyusheng
 * @Date: 2025/05/28
 */
@Slf4j
@RestController
@RequestMapping("/olca/flow/property")
public class PropertyController {

    @PostMapping("/add")
    public GlobalResponse<Long> add(@RequestBody PropertyRequest request) {

        var db = DataDir.get().openDatabase(DerbyConfig.DBNAME);

        var dao = new FlowPropertyDao(db);
        FlowProperty flowProperty = FlowProperty.of(
                request.getName(),
                db.get(UnitGroup.class, request.getUnitGroupRedId())
        );

        flowProperty.id = request.getId();
        flowProperty.refId = request.getRefId();

        // 持久化到数据库
        var result = dao.insert(flowProperty);
        db.close();

        return GlobalResponse.of(result.id);
    }

    @PostMapping("/update")
    public GlobalResponse<Long> update(@RequestBody PropertyRequest request) {

        var db = DataDir.get().openDatabase(DerbyConfig.DBNAME);
        var dao = new FlowPropertyDao(db);

        FlowProperty flowProperty = dao.getForId(request.getId());


        flowProperty.name = request.getName();
        if (StringUtils.isNotBlank(request.getUnitGroupRedId())) {
            flowProperty.unitGroup = db.get(UnitGroup.class, request.getUnitGroupRedId());
        }

        // 持久化到数据库
        var result = dao.update(flowProperty);
        db.close();

        return GlobalResponse.of(result.id);
    }

    @GetMapping("/delete/{id}")
    public GlobalResponse<String> delete(@PathVariable("id") String id) {

        var db = DataDir.get().openDatabase(DerbyConfig.DBNAME);
        new FlowPropertyDao(db).delete(Long.parseLong(id));
        db.close();

        return GlobalResponse.success();
    }

    @GetMapping("/get/{refId}")
    public GlobalResponse<FlowProperty> get(@PathVariable("refId") String refId) {

        var db = DataDir.get().openDatabase(DerbyConfig.DBNAME);
        var dao = new FlowPropertyDao(db);
        FlowProperty flowProperty = dao.getForRefId(refId);
        db.close();

        return GlobalResponse.of(flowProperty);
    }

    @GetMapping("/getAll")
    public GlobalResponse<List<FlowProperty>> getAll() {

        var db = DataDir.get().openDatabase(DerbyConfig.DBNAME);
        var dao = new FlowPropertyDao(db);
        List<FlowProperty> flowProperties = dao.getAll();
        db.close();

        return GlobalResponse.of(flowProperties);
    }

}
